package com.example.demo2.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.example.demo2.entity.Project;
import com.example.demo2.entity.Standard;
import com.example.demo2.mapper.ProjectMapper;
import com.example.demo2.mapper.StandardMapper;


import com.example.demo2.config.MapConfig;
import io.micrometer.observation.annotation.Observed;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;



import java.util.List;
import java.util.concurrent.ConcurrentHashMap;


/**
 * 标准和项目管理控制器
 * 处理标准和项目相关的HTTP请求
 */
@RestController
@CrossOrigin
public class hostController {
    @Autowired
    private StandardMapper standardmapper;
    @Autowired
    private ProjectMapper projectmapper;
    private ConcurrentHashMap<String, Integer> concurrentMap;

    @Autowired
    public void MyController(ConcurrentHashMap<String, Integer> concurrentMap) {
        this.concurrentMap = concurrentMap;
    }

    /**
     * 获取所有标准列表
     *
     * @return 标准列表
     */
    @GetMapping("/host")
    public List<Standard> host() {

        System.out.println("9999999999999999999999999999999999调用host");

        List<Standard> list = standardmapper.findAllStandard();
        if (list != null) {

            return list;
        } else return list;
    }//返回值为standard列表

    /**
     * 添加新的标准
     *
     * @param param 标准信息对象
     * @return 添加操作结果信息
     */
    @PutMapping("/AddStandard")
    public String AddStandard(@RequestBody Standard param) {
        System.out.println("这里是传输过来的值" + param.getStaName());
        Standard standard = new Standard();
        standard.setStaGB(param.getStaGB());
        standard.setStaName(param.getStaName());
        standard.setStaType(param.getStaType());
        int re = standardmapper.AddOneStandard(standard);
        if (re == 1)
            return "添加成功";
        else
            return "添加失败";
    }

    /**
     * 删除单个标准
     *
     * @param staId 标准ID
     * @return 删除操作结果信息
     */
    @DeleteMapping("/DeleteStandard")
    public String DeleteStandard(@RequestParam int staId) {
        int re = standardmapper.DeleteOneStandard(staId);
        if (re == 1)
            return "删除成功";
        else
            return "删除失败";
    }

    /**
     * 批量删除标准
     *
     * @param staIds 标准ID列表
     * @return 删除操作结果信息
     */
    @DeleteMapping("/DeleteMoreStandard")
    public String DeleteMoreStandard(@RequestBody List<Integer> staIds) {
        System.out.println("接收到的ID列表: " + staIds);  // 添加日志
        if (staIds == null || staIds.isEmpty()) {
            return "ID列表为空";
        }

        for (Integer id : staIds) {
            int re = standardmapper.DeleteOneStandard(id);
            if (re != 1) {
                System.out.println("删除ID " + id + " 失败");  // 添加日志
                return "删除失败";
            }
        }
        return "删除成功";
    }

    /**
     * 获取指定标准下的所有项目
     *
     * @param staId 标准ID
     * @return 项目列表
     */
    @GetMapping("/host/project")
    public List<Project> projectList(@RequestParam Integer staId) {//该值为查看standard在list中的对应下标
        Integer value = (Integer) concurrentMap.get("uID");
        System.out.println("成功获取到了uID" + value);
        //List<standard> list = ( List<standard>) session.getAttribute("standardList");
        System.out.println(staId);
        List<Project> plist = projectmapper.findAllProjectBysatId(staId);
        return plist;//返回该standard的全部project（未判断是否为空）
    }

    /**
     * 添加新项目
     *
     * @param project 项目信息对象
     * @return 添加操作结果信息
     */
    @PutMapping("/AddProject")
    public String AddProject(@RequestBody Project project) {
        System.out.println("这里是传入的值" + project.getPjName());
        int re = projectmapper.AddProject(project);
        if (re == 1)
            return "添加成功";
        else
            return "添加失败";
    }

    /**
     * 删除单个项目
     *
     * @param pjId 项目ID
     * @return 删除操作结果信息
     */
    @DeleteMapping("/DeleteProject")
    public String DeleteProject(int pjId) {
        int re = projectmapper.DeleteOneProject(pjId);
        if (re == 1)
            return "删除成功";
        else
            return "删除失败";
    }

    /**
     * 批量删除项目
     *
     * @param pjIds 项目ID列表
     * @return 删除操作结果信息
     */
    @DeleteMapping("/DeleteMoreProject")
    public String DeleteMoreProject(@RequestBody List<Integer> pjIds) {
        for (Integer id : pjIds) {
            int re = projectmapper.DeleteOneProject(id);
            if (re != 1)
                return "删除失败";
        }
        return "删除成功";
    }


    @PostMapping("/excelAddToStandard")
    public int excelAddToStandard(@RequestParam MultipartFile formData)throws Exception {

        System.out.println("UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU");

        InputStream inputStream = formData.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        List<List<Object>> rows = reader.read();
        //System.out.println("UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU"+rows);
        //System.out.println("YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY"+rows.get(0).get(0));
        List<Standard> standards = new ArrayList<>();
        List<Project> projects = new ArrayList<>();

        boolean flag = false;
        boolean key = true;

        //开始导入标准表单
        String sta = null;
        for (List<Object> row : rows) {
            if (standards.isEmpty() && row != null && !row.isEmpty() && !flag) {
                flag = true;
                System.out.println("UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU");
                continue; // 跳过标题行
            }
            if(key){
                sta = row.get(4).toString();
                key = false;

                Standard standard = new Standard();
                standard.setStaName(row.get(1).toString()); // 假设类别(产品/项目/参数)和标准名称在第二列
                standard.setStaGB(row.get(4).toString()); // 假设标准编号（含年号）在第五列
                String category = row.get(0).toString(); // 假设大类在第一列
                System.out.println("88888888888888888888888888888888888888"+category);
                standard.setStaType(category);
                standards.add(standard);
            }
            else
            {
                if(row.get(4).toString().equals(sta))
                {
                    continue;
                }
                else
                {
                    sta = row.get(4).toString();

                    Standard standard = new Standard();
                    standard.setStaName(row.get(1).toString()); // 假设类别(产品/项目/参数)和标准名称在第二列
                    standard.setStaGB(row.get(4).toString()); // 假设标准编号（含年号）在第五列
                    String category = row.get(0).toString(); // 假设大类在第一列
                    System.out.println("88888888888888888888888888888888888888"+category);
                    standard.setStaType(category);
                    standards.add(standard);

                }
            }

        }

        standardmapper.insertStandardList(standards);

        //开始导入项目
        flag = false;

        for (List<Object> row : rows) {

            if (projects.isEmpty() && row != null && !row.isEmpty() && !flag) {
                flag = true;
                System.out.println("222222222222222222222222222222222222222222222222222222222");
                continue; // 跳过标题行
            }

            Project project = new Project();
            project.setPjName(row.get(2).toString());
            String staGB = row.get(4).toString() + " " + row.get(5).toString();
            project.setPjGB(staGB);
            //寻找到staID根据GB
            int staId = projectmapper.findStaIdByGB(row.get(4).toString());
            project.setStaId(staId);
            projects.add(project);
        }


        return projectmapper.insertProjectList(projects);

    }
}
